package com.ciwong.epaper.modules.pad.model;

import android.text.TextUtils;

import com.ciwong.epaper.application.EApplication;
import com.ciwong.epaper.bean.LoginInfo;
import com.ciwong.epaper.bean.UserAccountInfo;
import com.ciwong.epaper.modules.login.LoginContract;
import com.ciwong.epaper.modules.login.LoginFinishedListener;
import com.ciwong.epaper.modules.me.dao.MeDao;
import com.ciwong.epaper.modules.pad.contentprovider.LoginToken;
import com.ciwong.epaper.util.AESCBCUtil;
import com.ciwong.epaper.util.EConstants;
import com.ciwong.epaper.util.SerializableManager;
import com.ciwong.libs.utils.CWSys;
import com.ciwong.libs.utils.DeviceUtils;
import com.ciwong.libs.utils.volley.BaseRequest;
import com.ciwong.libs.utils.volley.HttpRequest;
import com.ciwong.mobilelib.bean.DetailUserInfo;
import com.ciwong.mobilelib.bean.UserInfoBase;
import com.ciwong.mobilelib.i.BaseCallBack;
import com.ciwong.mobilelib.utils.BaseConstants;

import java.io.IOException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;


/**
 * 登录数据逻辑层实现
 * Created by lqi on 2017/2/22.
 */
public class PadLoginModelImpl implements LoginContract.LoginModel {

    private static final String TAG = "PadLoginModelImpl";


    private void saveUserBaseInfo(LoginInfo loginInfo, EApplication application, boolean isMobile, String password) {
        final UserInfoBase userInfoBase = new UserInfoBase();
        userInfoBase.setUserId(Long.parseLong(loginInfo.getUserId()));
        userInfoBase.setIsMobile(isMobile);
        userInfoBase.setAvatar(loginInfo.getAvatar());
        userInfoBase.setNickName(loginInfo.getNickName());
        userInfoBase.setMobile(loginInfo.getMobile());
        userInfoBase.setRealName(loginInfo.getRealName());
        application.setUserInfoBase(userInfoBase);
        EApplication.MOBILE = loginInfo.getMobile();
        final UserAccountInfo userAccountInfo = new UserAccountInfo();
        userAccountInfo.setPhoneNumber(loginInfo.getMobile());
        userAccountInfo.setPhonelogin(isMobile);
        userAccountInfo.setUserId(Long.parseLong(loginInfo.getUserId()));
        userAccountInfo.setUserPwd(password);
        userAccountInfo.setAvatar(loginInfo.getAvatar());

        try {

            CWSys.setSharedSerializable(BaseConstants.SHARE_KEY_USER_INFO_BASE, userInfoBase);
            CWSys.setSharedLong(BaseConstants.SHARE_PRE_CURR_LOGIN_USER, userInfoBase.getUserId());

            //清除用户学习班级信息
            CWSys.setSharedSerializable(SerializableManager.SerializeKey.SHARE_KEY_CHOOSE_SCHOOL + userInfoBase.getUserId(), null);
            SerializableManager.getInstance().serialize(SerializableManager.SerializeKey.SHARE_KEY_CLASS_DEFAULT, null);
            SerializableManager.getInstance().serialize(SerializableManager.SerializeKey.SHARE_KEY_CLASS_LIST, null);
            application.setSchoolDetail(null);
            application.setClazz(null);
            application.setClazzs(null);

            CWSys.setSharedString(EConstants.SHARE_PRE_CURR_LOGIN_USER_PHONE + SerializableManager.getInstance().getUserId(true), userInfoBase.getMobile());

        } catch (IOException e) {
            e.printStackTrace();
        }
        SerializableManager.getInstance().deSerialize(SerializableManager.SerializeKey.SHARE_KEY_USER_ACCOUNT_LIST,
                new BaseCallBack() {
                    @Override
                    public void success(Object data) {
                        List<UserAccountInfo> userAccountList;
                        if (data instanceof List) {
                            userAccountList = (ArrayList<UserAccountInfo>) data;
                        } else {
                            userAccountList = new ArrayList<>();
                        }
                        if (EConstants.IS_YOUKE) {
                            //DO NOTHING
                        } else {
                            for (int i = 0; i < userAccountList.size(); i++) {
                                if (userAccountList.get(i).getUserId() == userAccountInfo.getUserId()) {
                                    userAccountList.remove(i);
                                }
                            }
                            //如果是免密码登录，只记住一个用户名
                            if ("100151".equals(EConstants.CLIENT_ID)) {
                                userAccountList.clear();
                            }
                            userAccountList.add(0, userAccountInfo);
                            SerializableManager.getInstance().serialize(
                                    SerializableManager.SerializeKey.SHARE_KEY_USER_ACCOUNT_LIST,
                                    (Serializable) userAccountList, false);
                        }


                    }

                    @Override
                    public void failed(int errorCode, Object data) {
                        createUerLoginList(userAccountInfo);
                    }

                    @Override
                    public void failed(Object data) {
                        createUerLoginList(userAccountInfo);
                    }

                }, false);

    }

    private static void createUerLoginList(UserAccountInfo userAccountInfo) {
        List<UserAccountInfo> userInfoBaseList = new ArrayList<>();
        userInfoBaseList.add(userAccountInfo);
        SerializableManager.getInstance().serialize(SerializableManager.SerializeKey.SHARE_KEY_USER_ACCOUNT_LIST,
                (Serializable) userInfoBaseList, false);
    }


    public void saveTokenInfo(LoginInfo info) {
        BaseRequest.VerifyInfo verifyInfo = new BaseRequest.VerifyInfo();
        verifyInfo.setAccessToken(info.getAccessToken());
        verifyInfo.setClientId(EConstants.CLIENT_ID);
        verifyInfo.setClientIp(DeviceUtils.getLocalIpAddress());
        verifyInfo.setOauthVersion("2.0");
        verifyInfo.setScope("all");
        verifyInfo.setRefreshToken(info.getRefreshToken());
        verifyInfo.setExpiresIn(info.getExpiresIn());
        try {
            CWSys.setSharedSerializable(BaseConstants.SHARE_KEY_VERITIFY_INFO,
                    verifyInfo);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {

            HttpRequest.setVerifyInfo(verifyInfo);
        }
    }

    @Override
    public void login(final EApplication application, String usernameStr, final String passwordBefor, String uuid, String captchaCode, final LoginFinishedListener listener, final boolean isMobile) {
        final String passWord = AESCBCUtil.encrypt(passwordBefor, AESCBCUtil.AESCBC_HEX);
        final String userName = AESCBCUtil.encrypt(usernameStr, AESCBCUtil.AESCBC_HEX);
        MeDao.getInstance().getUserToken(application, userName, passWord, uuid, captchaCode, new BaseCallBack() {
            @Override
            public void success(Object data) {
                final LoginInfo loginInfo = (LoginInfo) data;
                if (null != loginInfo.getMobile() && loginInfo.getMobile().length() > 0) {
                    loginInfo.setMobile(AESCBCUtil.decrypt(loginInfo.getMobile(), AESCBCUtil.AESCBC_HEX));
                }
                saveTokenInfo(loginInfo);
                MeDao.getInstance().getDetailUserInfo(new BaseCallBack() {
                    @Override
                    public void failed(int errorCode, Object data) {
                        //默认是学生
                        saveUserInfoAndToken(loginInfo, application, isMobile, passWord, null);
                        listener.onLoginSuccess(!TextUtils.isEmpty(loginInfo.getMobile()), passwordBefor);
                    }

                    @Override
                    public void failed(Object data) {
                        //默认是学生
                        saveUserInfoAndToken(loginInfo, application, isMobile, passWord, null);
                        listener.onLoginSuccess(!TextUtils.isEmpty(loginInfo.getMobile()), passwordBefor);
                    }

                    @Override
                    public void success(Object data) {
                        DetailUserInfo detailUserInfo = null;
                        if (data != null && data instanceof DetailUserInfo) {
                            detailUserInfo = (DetailUserInfo) data;
                        }
                        saveUserInfoAndToken(loginInfo, application, isMobile, passWord, detailUserInfo);
                        listener.onLoginSuccess(!TextUtils.isEmpty(loginInfo.getMobile()), passwordBefor);
                    }
                });


            }

            @Override
            public void failed(int errorCode, Object data) {

                listener.onLoginFiled(errorCode, String.valueOf(data));
            }

            @Override
            public void failed(Object data) {
                listener.onLoginFiled(data);
            }
        });


    }

    private void saveUserInfoAndToken(LoginInfo loginInfo, EApplication application, boolean isMobile, String passWord, DetailUserInfo detailUserInfo) {
        saveUserBaseInfo(loginInfo, application, isMobile, passWord);
        LoginToken.saveTokenInfoToContentProividerByPad(application, loginInfo, detailUserInfo);
    }

}
